<template>
  <section class="todoapp">
    <todolistHeader @addList="addList"></todolistHeader>
    <todolistBody
      :list="renderList"
      @changeFlag="changeFlag"
      @changeAll="changeAll"
      @delList="delList"
    ></todolistBody>
    <todolistFooter
      :sum="sum"
      :type="type"
      @changeType="changeType"
      :isShowBtn="isShowBtn"
      @delAll="delAll"
    ></todolistFooter>
  </section>
</template>

<script>
import todolistHeader from './components/todolistHeader.vue'
import todolistBody from './components/todolistBody.vue'
import todolistFooter from './components/todolistFooter.vue'

export default {
  components: {
    todolistHeader,
    todolistBody,
    todolistFooter,
  },
  data() {
    return {
      list: [
        {
          flag: true,
          id: 1,
          value: '读万卷书',
        },
        {
          flag: false,
          id: 2,
          value: '行万里路',
        },
      ],
      type: 'all',
    }
  },
  methods: {
    addList(value) {
      this.list = [
        ...this.list,
        {
          flag: true,
          id: +new Date(),
          value,
        },
      ]
    },
    changeFlag(id, flag) {
      this.list.forEach((item) => {
        if (item.id === id) item.flag = flag
      })
    },
    delList(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    changeAll(flag) {
      this.list.forEach((item) => (item.flag = flag))
    },
    changeType(value) {
      this.type = value
    },
    delAll() {
      this.list = this.list.filter((item) => !item.flag)
    },
  },
  computed: {
    sum() {
      return this.list.filter((item) => !item.flag).length
    },
    isShowBtn() {
      return this.list.some((item) => item.flag)
    },
    renderList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },
  },
  // watch: {
  //   list: {
  //     deep: true,
  //     handler(newVal) {
  //       localStorage.setItem('list', JSON.stringify(newVal))
  //     },
  //   },
  // },
}
</script>

<style></style>
